package com.db.protocol;

import com.db.protocol.exception.InvalidMessageProtocolException;
import com.db.protocol.exception.ParseProtocolException;
import com.db.protocol.tags.MsgType;
import com.db.protocol.tags.Tag;

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/**
 *
 * @author nulls.narik
 */
public abstract class AbstractFixProtocol {

    protected static final String PARSING_PAIR = "\\|";

    protected static final String PARSING_KEY_AND_VALUE = "=";

    protected Map<Tag, String> parse(String message) throws ParseProtocolException {
        if (message == null) {
            throw new InvalidMessageProtocolException(message);
        }

        Map<Tag, String> result = new HashMap<Tag, String>();

        Scanner scanner = new Scanner(message);
        scanner.useDelimiter(PARSING_PAIR);
        try {
            while (scanner.hasNext()) {
                String pair = scanner.next();
                String[] arguments = pair.split(PARSING_KEY_AND_VALUE);
                if (arguments.length != 2) {
                    scanner.close();
                    throw new InvalidMessageProtocolException(pair);
                }

                result.put(Tag.parse(arguments[0]), arguments[1]);
            }
        } finally {
            scanner.close();
        }
        return result;
    }


}
